use ggez::{glam::Vec2, Context, graphics::{self, Rect}, mint::Point2};
use crate::particle;




pub struct Shape {
    particles: Vec<particle::Particle>,
    origin: Vec2,
    size: Vec2,
    is_broken: bool,
    lifespan: f32
}

impl Shape {
    pub fn new(origin: Vec2, size: Vec2) -> Shape {
        let particles: Vec<particle::Particle> = vec![];
        let is_broken = false;
        let lifespan = 1.0;
        Shape { particles, origin, size, is_broken, lifespan }
    }

    pub fn is_dead(&self) -> bool {
        if self.lifespan <= 0.0 && self.particles.len() == 0 {
            true
        } else {
            false
        }
    }

    fn is_in_me(&mut self, p: Point2<f32>) -> bool {
        p.x >= self.origin.x && p.x <= self.origin.x+self.size.x && p.y >= self.origin.y && p.y <= self.origin.y+self.size.y
    }

    pub fn update (&mut self, ctx: &mut Context) -> () {
        if self.is_broken {
            if self.particles.len() == 0 {
                let xstep = self.size.x/10.0;
                let ystep = self.size.y/10.0;
                for i in 0..10 {
                    for j in 0..10 {
                        let mut origin = self.origin;
                        origin.x += xstep*i as f32;
                        origin.y += ystep*j as f32;
                        let size = Vec2{x: xstep, y: ystep};
                        let velocity = (origin-Vec2{x: ctx.mouse.position().x, y: ctx.mouse.position().y})*0.1;
                        let particle = particle::Particle::new(origin, size, velocity);
                        self.particles.push(particle);
                    }
                }
            }
            self.lifespan -= 0.01;
            

            self.particles.retain_mut(|particle| {
                let fg = Vec2{x: 0.0, y: 0.1} * particle.get_mass();
                particle.apply_force(fg);
                particle.update();
                !particle.is_dead()
            });
        } else {
            if ctx.mouse.button_just_pressed(ggez::event::MouseButton::Left) && self.is_in_me(ctx.mouse.position()) {
                self.is_broken = true
            }
        }
    }

    pub fn display (&mut self, ctx: &mut Context, canvas : &mut graphics::Canvas) -> () {
        if self.is_broken{
            for particle in &mut self.particles {particle.display(ctx, canvas)};
        } else {
            let rect = graphics::Mesh::new_rectangle(
                ctx, 
                graphics::DrawMode::fill(), 
                Rect { x: self.origin.x, y: self.origin.y, w: self.size.x, h: self.size.y } , 
                graphics::Color::new(0.7, 0.7, 0.7, self.lifespan)).unwrap();
            canvas.draw(&rect, graphics::DrawParam::default()); 
        }
    }
}